import base64
import json
from Crypto.Cipher import AES

# 微信敏感信息解码
def decrypt(appId, sessionKey, encryptedData, iv):
        # base64 decode
        sessionKey = base64.b64decode(sessionKey)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        decrypted = json.loads(_unpad(cipher.decrypt(encryptedData)))

        if decrypted['watermark']['appid'] != appId:
            raise Exception('Invalid Buffer')

        return decrypted

def _unpad(s):
    return s[:-ord(s[len(s)-1:])]